package com.leinao.core.schedule;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.leinao.core.pool.DevicePointInfoPool;
import com.leinao.core.pool.TableInfoPool;
import com.leinao.domain.DeviceData;
import com.leinao.domain.PointInfo;
import com.leinao.domain.TableInfo;
import com.leinao.domain.param.DeviceDataQueryParam;
import com.leinao.service.TdengingService;
import com.leinao.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * description
 *
 * @author zhong.wang
 * @date 2025/1/16
 */
@Component
@Slf4j
public class ScheduleTask {
    @Value("${remote.add-data-interface}")
    private String remoteInterface;

    @Resource
    private TdengingService tdengingService;

    /**
     *
     * @throws ParseException
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void tasks() throws ParseException{
        Date lastSyncTime = tdengingService.getLastSyncTime();
        Date nextTime = DateUtils.addMinutes(lastSyncTime, 15);

        Date dbStartTime = getDbTime(lastSyncTime);
        Date dbEndTime = getDbTime(nextTime);

        Long durationDays = DateUtils.getDurationDays(dbStartTime,lastSyncTime);
        Date startTime = DateUtils.addDays(dbStartTime, Math.toIntExact(durationDays));
        Date endTime = DateUtils.addDays(dbEndTime,Math.toIntExact(durationDays));

        if(startTime.after(new Date()) || endTime.after(new Date()) ){
            return;
        }

        log.info("同步db开始时间：" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dbStartTime));
        log.info("同步db结束时间：" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dbEndTime));
        log.info("同步开始时间：" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,startTime));
        log.info("同步结束时间：" + DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,endTime));
        log.info("-----------------------------------");



        Map<Long, List<TableInfo>> tableInfoPool = TableInfoPool.getInstance().getTableInfoPool();

        for(Map.Entry<Long,List<TableInfo>> entry : tableInfoPool.entrySet()){
            Long deviceModelId = entry.getKey();
            String sTableName = "device_model_" + deviceModelId;
            List<TableInfo> tableInfos = entry.getValue();
            for (TableInfo tableInfo : tableInfos) {
                DeviceDataQueryParam queryParam = new DeviceDataQueryParam();
                queryParam.setTableName(tableInfo.getTbname());
                queryParam.setStartTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dbStartTime));
                queryParam.setEndTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,dbEndTime));
                queryParam.setTimeGroupInterval(durationDays+"d");
                List<DeviceData> dataList = tdengingService.getDataAndAddDay(queryParam);

                List<PointInfo> pointInfos = new ArrayList<>();
                for (DeviceData deviceData : dataList) {
                    Long pointId = deviceData.getPointId();
                    PointInfo info = DevicePointInfoPool.getInstance().getById(pointId);
                    if(Objects.nonNull(info)){
                        PointInfo clone = (PointInfo) info.clone();
                        clone.setSuperTableName(sTableName);
                        clone.setChildTableName(tableInfo.getTbname());
                        clone.setDataValue(deviceData.getDataValue());
                        clone.setTs(deviceData.getTs());
                        pointInfos.add(clone);
                    }
                }
                if(CollectionUtil.isNotEmpty(pointInfos)){

                    log.info(sTableName + ": " + tableInfo.getTbname() + " remote request size "+ pointInfos.size());
                    try {
                        sendToBatchSave(pointInfos);
                    } catch (Exception e) {
                        removeDirtyData(dbStartTime,dbEndTime,durationDays);
                        log.info(e.getMessage());
                        return;
                    }
                }
            }
        }
        tdengingService.updateSyncTime(nextTime);
    }

    /**
     * 删除脏数据
     * @param startTime
     * @param endTime
     */
    public void removeDirtyData(Date startTime,Date endTime,Long duration){
        startTime = DateUtils.addDays(startTime, Math.toIntExact(duration));
        endTime = DateUtils.addDays(endTime,Math.toIntExact(duration));

        List<Long> deviceModelIdPool = TableInfoPool.getInstance().getDeviceModelIdPool();
        if(CollectionUtil.isNotEmpty(deviceModelIdPool)){
            for (Long aLong : deviceModelIdPool) {
                DeviceDataQueryParam queryParam = new DeviceDataQueryParam();
                String tableName = "device_model_" + aLong;
                queryParam.setTableName(tableName);
                queryParam.setStartTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,startTime));
                queryParam.setEndTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,endTime));
                tdengingService.deleteDataByTs(queryParam);
            }
        }
    }

    /**
     * 发送
     * @param pointInfos
     */
    public void sendToBatchSave(List<PointInfo> pointInfos) throws Exception {

        String url = remoteInterface; // 确保这里已经正确设置了远程接口URL
        String jsonParam = JSONUtil.toJsonStr(pointInfos);

        // 发送 POST 请求并获取响应结果
        String response = HttpUtil.post(url, jsonParam);

        // 将响应字符串转换为 JSONObject
        JSONObject jsonResponse = JSONUtil.parseObj(response);

        // 获取 message 对象中的 code 和 message 字段
        JSONObject messageObj = jsonResponse.getJSONObject("message");
        int code = messageObj.getInt("code", -1); // 使用默认值-1以便在找不到'code'时也能处理

        if (code != 200) {
            // 如果状态码不是 200，则抛出异常
            throw new RuntimeException("Request failed with status code: " + code);
        }
    }

    /**
     * 获取db 时间
     * @param time
     * @return
     */
    public Date getDbTime(Date time){
        Date res = null;
        try {
            String s = DateUtils.parseDateToStr("dd HH:mm:ss", DateUtils.dateMod10(time));
            String timeStr = "2024-12-" + s;
            res = DateUtils.parseDate(timeStr,DateUtils.YYYY_MM_DD_HH_MM_SS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

}
